package service

import (
	"context"
	"fmt"
	"mini-app/config/mysql"
	"mini-app/internal/app/grpc/common"
	"mini-app/internal/dal"
	"mini-app/internal/dao"
	"mini-app/internal/models"
	"strings"

	"192.168.1.75/go-pkg/errorx"
	"github.com/samber/lo"
)

type Goods struct{}

type GoodsListT struct {
	GoodsID        string  `json:"goods_id"`                  // 商品ID
	GoodsName      string  `json:"goods_name"`                // 商品名称
	Price          float64 `json:"price"`                     // 商品价格
	GoodsImage     string  `json:"goods_image"`               // 商品图片
	RecommendImage string  `json:"recommend_image"`           // 推荐图片
	AdImage        string  `json:"ad_image"`                  // 商品广告
	GoodsCode      string  `json:"goods_code"`                // 国标编码
	PickupType     string  `json:"pickup_type"`               // 取货方式，多个以逗号分隔
	GoodsType      int     `json:"goods_type"`                // 商品类型，
	GoodsTag       string  `json:"goods_tag,omitempty"`       // 商品标签
	CornerLabel    string  `json:"corner_label,omitempty"`    // 脚标，多个以逗号分隔
	GoodsInventory int     `json:"goods_inventory,omitempty"` // 库存量
}

// List 商品列表
func (Goods) List(
	ctx context.Context,
	robotID string,
	classID string,
	page, limit int,
) (
	list []*GoodsListT,
	total int64,
	err error,
) {
	goodsType := 0
	if robotID == "" {
		return []*GoodsListT{}, 0, errorx.New("设备id不能为空", -1)
	}
	goodsIDs := []string{}
	goodsMap := make(map[string]*GoodsListT)
	goodsList, _ := common.GRPC{}.GetGoodsList(ctx, robotID, goodsType, 0, "", "", 1, 0)
	// 初始化新的商品
	for _, record := range goodsList {
		goodsIDs = append(goodsIDs, record.GoodsId)
		goodsMap[record.GoodsId] = &GoodsListT{
			GoodsID:        record.GoodsId,
			GoodsName:      record.GoodsName,
			GoodsImage:     record.GoodsImage,
			RecommendImage: record.RecommendImage,
			AdImage:        record.AdImage,
			Price:          record.GoodsPrice,
			GoodsType:      int(record.GoodsType),
			GoodsInventory: int(record.GoodsInventory),
		}
	}
	// 获取商品配置
	// 以零售后台存在的产品为主，所以这里必须以goodsIDs作为过滤
	settings, total, _ := dao.GoodsSetting{}.List(
		ctx,
		dal.Q,
		robotID,
		goodsIDs,
		classID,
		1,
		page, limit,
	)
	for _, setting := range settings {
		record := goodsMap[setting.GoodsID]
		if record == nil {
			continue
		}
		record.PickupType = setting.PickupType
		record.GoodsTag = setting.Tag
		record.CornerLabel = setting.CornerLabel
		list = append(list, record)
	}
	return
}

type GoodsDetailT struct {
	GoodsID         string  `json:"goods_id"`          // 商品ID
	GoodsName       string  `json:"goods_name"`        // 商品名称
	Price           float64 `json:"price"`             // 商品价格
	GoodsImage      string  `json:"goods_image"`       // 商品图片
	GoodsType       int     `json:"goods_type"`        // 商品类型，
	RecommendImage  string  `json:"recommend_image"`   // 推荐图
	AdImage         string  `json:"ad_image"`          // 广告图
	Detail          string  `json:"detail"`            // 商品详情
	ReviewPoints    int     `json:"review_points"`     // 评测奖励积分
	Tags            string  `json:"tags"`              // 商品标签
	CheckGenderType int     `json:"check_gender_type"` // 性别限制[1:男 2:女 3:不限制 ]

	// 以下是导流新增字段
	GoodsGuideType       string `json:"goods_guide_type"` // 导流类型[QR二维码 ShareCode口令]
	GoodsGuideUrl        string `json:"goods_guide_url"`  // 导流URL
	GoodsGuideTargetUrl  string `json:"goods_guide_target_url"`
	ShareCodeType        string `json:"share_code_type"`    // 口令导流类型[TaoBao\DouYin\JD\XiaoHongShu]
	ShareCode            string `json:"share_code"`         // 导流分享码
	GoodsGuideNotice     string `json:"goods_guide_notice"` // 导流提示 须知
	GoodsGuideButtonText string `json:"goods_guide_button_text"`
}

// Detail 商品详情
func (Goods) Detail(
	ctx context.Context,
	goodsID string,
	robotID string,
) (*GoodsDetailT, error) {
	// grpc获取商品详情
	goodsDetail := common.GRPC{}.GoodsDetail(ctx, goodsID)
	if goodsDetail == nil {
		return nil, fmt.Errorf("商品不存在")
	}
	// 获取商品标签
	var goodsSetting []*models.GoodsSetting
	if goodsID != "" && robotID != "" {
		goodsSetting, _, _ = dao.GoodsSetting{}.List(
			ctx,
			dal.Q,
			robotID,
			[]string{goodsID},
			"",
			0,
			1,
			1,
		)
	}
	var tags string
	if len(goodsSetting) > 0 {
		tags = goodsSetting[0].Tag
	}

	return &GoodsDetailT{
		GoodsID:         goodsDetail.GoodsId,
		GoodsName:       goodsDetail.GoodsName,
		Price:           goodsDetail.GoodsPrice,
		GoodsImage:      goodsDetail.GoodsImage,
		GoodsType:       int(goodsDetail.GoodsType),
		RecommendImage:  goodsDetail.RecommendImage,
		AdImage:         goodsDetail.AdImage,
		Detail:          goodsDetail.Detail,
		ReviewPoints:    int(goodsDetail.ReviewPoints),
		Tags:            tags,
		CheckGenderType: int(goodsDetail.CheckGenderType),

		GoodsGuideType:       goodsDetail.GoodsGuideType,
		GoodsGuideUrl:        goodsDetail.GoodsGuideUrl,
		GoodsGuideTargetUrl:  goodsDetail.GoodsGuideTargetUrl,
		ShareCodeType:        goodsDetail.ShareCodeType,
		ShareCode:            goodsDetail.ShareCode,
		GoodsGuideNotice:     goodsDetail.GoodsGuideNotice,
		GoodsGuideButtonText: goodsDetail.GoodsGuideButtonText,
	}, nil
}

type GoodsReviewT struct {
	WechatName   string `json:"wechat_name" gorm:"-"`             // 微信名称
	WeChatAvatar string `json:"wechat_avatar,omitempty" gorm:"-"` // 微信头像
	Star         string `json:"star" gorm:"column:star"`          // 星级
	Content      string `json:"content" gorm:"column:content"`    // 评价内容
	Images       string `json:"images" gorm:"column:images"`      // 评测的图片
}

func (Goods) Review(
	ctx context.Context,
	goodsID string,
	page, limit int,
) (list []GoodsReviewT, total int64) {
	if goodsID == "" {
		return []GoodsReviewT{}, 0
	}
	records, total := dao.GoodsReview{}.List(
		ctx,
		mysql.NewDB(),
		"", goodsID,
		0, "", 1, 1,
		1,
		0, 0,
		page, limit,
	)
	for _, record := range records {
		var wechatName = ""
		var weChatAvatar = ""
		userDetail, _ := dao.User{}.UserInfo(ctx, dal.Q, record.OpenID, "", "")
		if userDetail != nil {
			wechatName = userDetail.NickName
			weChatAvatar = userDetail.Image
		}
		list = append(list, GoodsReviewT{
			WechatName:   wechatName,
			WeChatAvatar: weChatAvatar,
			Star:         record.Star,
			Content:      record.Content,
			Images:       record.Images,
		})
	}
	if len(list) == 0 {
		list = []GoodsReviewT{}
	}
	return
}

type LatestOrderT struct {
	GoodsID      string `json:"goods_id"`      // 商品id
	WechatName   string `json:"wechat_name"`   // 微信名称
	WechatAvatar string `json:"wechat_avatar"` // 微信头像
	CreatedAt    int64  `json:"created_at"`    // 创单时间
}

func (Goods) LatestOrder(
	ctx context.Context,
	goodsID string,
	page, limit int,
) (list []LatestOrderT, total int64) {
	records, total := dao.Goods{}.LastestOrder(ctx, mysql.NewDB(), goodsID, page, limit)
	for _, record := range records {
		var wechatName, wechatAvatar string
		userDetail, _ := dao.User{}.UserInfo(ctx, dal.Q, record.Openid, "", "")
		if userDetail != nil {
			wechatName = userDetail.NickName
			wechatAvatar = userDetail.Image
		}
		list = append(list, LatestOrderT{
			GoodsID:      record.GoodsID,
			WechatName:   wechatName,
			WechatAvatar: wechatAvatar,
			CreatedAt:    record.CreatedAt,
		})
	}
	if len(list) == 0 {
		return []LatestOrderT{}, 0
	}
	return
}

type GoodsClassT struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

func (Goods) ClassList(
	ctx context.Context,
	robotID string,
) (list []GoodsClassT, err error) {
	records, _ := dao.Goods{}.ClassList(ctx, dal.Q, robotID)
	if len(records) == 0 {
		return []GoodsClassT{}, nil
	}
	for _, record := range records {
		var className string
		classIDs := strings.Split(record.GoodsClass, ",")
		for _, classID := range classIDs {
			detail, _ := dao.GoodsClass{}.Detail(ctx, dal.Q, classID)
			if detail != nil {
				className = detail.Name
			}
			list = append(list, GoodsClassT{
				ID:   classID,
				Name: className,
			})
		}
	}
	list = lo.Uniq(list)
	return list, nil
}
